package com.uu.safeguard.service.impl;

import com.uu.safeguard.dao.MemberDao;
import com.uu.safeguard.entity.Member;
import com.uu.safeguard.service.MemberService;
import com.uu.safeguard.utils.CommonUtil;
import com.uu.safeguard.utils.DbUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * (Member)表服务实现类
 *
 * @author makejava
 * @since 2021-03-19 09:59:59
 */
@Service("memberService")
public class MemberServiceImpl implements MemberService {
    @Resource
    private MemberDao memberDao;
    /**
     * @Description: 查询超级权限
     * @Param: [sn]
     **/
    @Override
    public LinkedHashMap<String, Object> findMemberRoleId(String sn) {
        return memberDao.findMemberRoleId(sn);
    }

    /**
     * @Description: 搜索用户
     * @Param: [memberSn]
     **/
    @Override
    public LinkedHashMap<String, Object> searchMemberBySn(String memberSn) {
        return memberDao.searchMemberBySn(memberSn);
    }

    /**
     * @Description: 查询高级身份
     * @Param: [sn]
     **/
    @Override
    public LinkedHashMap<String,Object> findAdvancedIdentity(String sn) {
        return memberDao.findAdvancedIdentity(sn);
    }

    /**
     * @Description: 权限校验用户
     * @Param: [sn]
     **/
    @Override
    public LinkedHashMap<String, Object> findMemberBySn(String sn) {
        return memberDao.findMemberBySn(sn);
    }

    /**
     * @Description: 用户数量饼状图
     * @Param: [operatorMemberSn, projectSn]
     **/
    @Override
    public LinkedHashMap<String, Object> findMemberPieChart(String operatorMemberSn, String projectSn) {
        return memberDao.findMemberPieChart(operatorMemberSn,projectSn);
    }

    /**
     * @Description: 余额柱状图
     * @Param: [operatorMemberSn, projectSn]
     **/
    @Override
    public LinkedHashMap<String, Object> findBalanceHistogram(String operatorMemberSn, String projectSn) {
        return memberDao.findBalanceHistogram(operatorMemberSn,projectSn);
    }

    /**
     * @Description: 某运营商某小区某日用户增长
     * @Param: [operatorMemberSn, projectSn, startTime, endTime]
     **/
    @Override
    public LinkedHashMap<String, Object> findMemberNewlyAddedOneDay(String operatorMemberSn, String projectSn, Long startTime, Long endTime) {
        return memberDao.findMemberNewlyAddedOneDay(operatorMemberSn,projectSn,startTime,endTime);
    }

    /**
     * @Description: 余额转让总计
     * @Param: [sn]
     **/
    @Override
    public LinkedHashMap<String, Object> findBalanceMoveAll(String sn) {
        return memberDao.findBalanceMoveAll(sn);
    }

    /**
     * @Description: 用户余额转账列表
     * @Param: [sn, startIndex, endIndex]
     **/
    @Override
    public List<LinkedHashMap<String, Object>> findBalanceMoveList(String sn, int pageIndex, int pageSize) {
        return memberDao.findBalanceMoveList(sn,(pageIndex-1)*pageSize,pageSize);
    }

    @Override
    public Integer findBalanceMoveListCount(String sn) {
        return memberDao.findBalanceMoveListCount(sn);
    }

    /**
     * @Description: 用户充值列表
     * @Param: [projectSn, sn, startIndex, endIndex]
     **/
    @Override
    public List<LinkedHashMap<String, Object>> findMemberRechargeList(String operatorMemberSn,String projectSn, String sn, int pageIndex, int pageSize) {
        return memberDao.findMemberRechargeList(operatorMemberSn,projectSn,sn,(pageIndex-1)*pageSize,pageSize);
    }

    @Override
    public Integer findMemberRechargeListCount(String operatorMemberSn,String projectSn, String sn) {
        return memberDao.findMemberRechargeListCount(operatorMemberSn,projectSn,sn);
    }

    /**
     * @Description: 项目用户消费利润列表
     * @Param: [sn, pageIndex, pageSize]
     **/
    @Override
    public List<LinkedHashMap<String, Object>> findMemberConsumeList(String operatorMemberSn,String projectSn,String stationSn,String sn, int pageIndex, int pageSize) {
        return memberDao.findMemberConsumeList(operatorMemberSn,projectSn,stationSn,sn,(pageIndex-1)*pageSize,pageSize);
    }

    @Override
    public Integer findMemberConsumeListCount(String operatorMemberSn, String projectSn, String stationSn, String sn) {
        return memberDao.findMemberConsumeListCount(operatorMemberSn,projectSn,stationSn,sn);
    }

    /**
     * @Description: 查询用户余额转让次数
     * @Param: [sn]
     **/
    @Override
    public LinkedHashMap<String, Object> findMemberMoneyMakeOver(String sn) {
        return memberDao.findMemberMoneyMakeOver(sn);
    }
    /**
     * @Description: 查询用户是否充电
     * @Param: [sn]
     **/
    @Override
    public LinkedHashMap<String, Object> findMemberIsCharge(String sn) {
        return memberDao.findMemberIsCharge(sn);
    }
    /**
     * @Description: 查询用户充值金额及次数
     * @Param: [sn]
     **/
    @Override
    public LinkedHashMap<String, Object> findMemberRechargeMsg(String sn,String operatorMemberSn) {
        return memberDao.findMemberRechargeMsg(sn,operatorMemberSn);
    }
    /**
     * @Description: 查询用户消费金额及次数
     * @Param: [sn]
     **/
    @Override
    public LinkedHashMap<String, Object> findMemberConsumeMsg(String sn,String operatorMemberSn,String stationSn) {
        return memberDao.findMemberConsumeMsg(sn,operatorMemberSn,stationSn);
    }

    /**
     * @Description: 查询用户及所在小区
     * @Param: [sn, projectSn]
     **/
    @Override
    public LinkedHashMap<String, Object> findMemberAndProject(String sn) {
        return memberDao.findMemberAndProject(sn);
    }

    /**
     * @Description: 小区用户明细（注册时间、账号、手机号）
     * @Param: [pageIndex, pageSize]
     **/
    @Override
    public List<LinkedHashMap<String, Object>> findProjectUserList(String sn,String projectSn,String keywords,Integer pageIndex, Integer pageSize) {
        return memberDao.findProjectUserList(sn,projectSn,keywords,(pageIndex-1)*pageSize,pageSize);
    }

    @Override
    public Integer findProjectUserListCount(String sn, String projectSn, String keywords) {
        return memberDao.findProjectUserListCount(sn,projectSn,keywords);
    }

    /**
     * @Description: 小区挂失用户
     * @Param: [sn, projectSn]
     **/
    @Override
    public LinkedHashMap<String, Object> findMyUserLose(String sn, String projectSn) {
        return memberDao.findMyUserLose(sn,projectSn);
    }
    /**
     * @Description: 小区退款用户
     * @Param: [sn, projectSn]
     **/
    @Override
    public LinkedHashMap<String, Object> findMyUserRefund(String sn, String projectSn) {
        return memberDao.findMyUserRefund(sn,projectSn);
    }

    /**
     * @Description: 各项目用户对比
     * @Param: [sn, timeStamp, projectSn]
     **/
    @Override
    public List<LinkedHashMap<String, Object>> findMyUserProjectContrast(String sn, long timeStamp, String projectSn) {
        return memberDao.findMyUserProjectContrast(sn,timeStamp,projectSn);
    }

    @Override
    public List<LinkedHashMap<String, Object>> findMyUserProjectContrast(String sn, long timeStamp, Integer pageIndex, Integer pageSize) {
        return memberDao.findMyUserProjectContrast(sn,timeStamp,(pageIndex-1)*pageSize,pageSize);
    }

    @Override
    public Integer findMyUserProjectContrastCount(String sn, long timeStamp, String projectSn) {
        return memberDao.findMyUserProjectContrastCount(sn,timeStamp,projectSn);
    }

    /**
     * @Description: 某月用户消费次数
     * @Param: [sn, timeStampStart, timeStampEnd, projectSn]
     **/
    @Override
    public List<LinkedHashMap<String, Object>> findMyUserMonthFrequency(String sn, long timeStampStart, long timeStampEnd, String projectSn) {
        return memberDao.findMyUserMonthFrequency(sn,timeStampStart,timeStampEnd,projectSn);
    }

    /**
     * @Description: 我的用户变化曲线
     * @Param: [sn, timeStamp, projectSn]
     **/
    @Override
    public List<LinkedHashMap<String, Object>> findMyUserChangeCurve(String sn, long timeStamp, String projectSn) {
        return memberDao.findMyUserChangeCurve(sn,timeStamp,projectSn);
    }

    /**
     * @Description: 我的用户数据统计
     * @Param: [sn]
     **/
    @Override
    public LinkedHashMap<String, Object> findMyUserStatistics(String sn,long timeStamp,String projectSn) {
        return memberDao.findMyUserStatistics(sn,timeStamp,projectSn);
    }
    /**
     * @Description: 描述 我的用户消费
     * @Param: [sn, projectSn]
     **/
    @Override
    public LinkedHashMap<String, Object> findMyUserConsume(String sn, String projectSn) {
        return memberDao.findMyUserConsume(sn,projectSn);
    }


    /**
     * 通过ID查询单条数据
     *
     * @param sn 主键
     * @return 实例对象
     */
    @Override
    public Member queryBySn(String sn) {
        return this.memberDao.queryBySn(sn);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<Member> queryAllByLimit(int offset, int limit) {
        return this.memberDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param member 实例对象
     * @return 实例对象
     */
    @Override
    public Member insert(Member member) {
        this.memberDao.insert(member);
        return member;
    }

    /**
     * 修改数据
     *
     * @param member 实例对象
     * @return 实例对象
     */
    @Override
    public Member update(Member member) {
        this.memberDao.update(member);
        return this.queryBySn(member.getSn());
    }

    /**
     * 通过主键删除数据
     *
     * @param sn 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteBySn(String sn) {
        return this.memberDao.deleteBySn(sn) > 0;
    }

    @Override
    public List<LinkedHashMap<String, Object>> queryBySnList(String sn) {
        return memberDao.queryBySnList(sn);
    }


    @Override
    public String otherLogin(Map member, Map platform ){
        if (member.size() == 0){
            return "";
        }
        if (platform.size() == 0){
            return "";
        }

        String member_type = member.get("type").toString();
        String platform_sn = platform.get("sn").toString();

        DbUtil db = new DbUtil();
        //判断会员是否存在
        List where = new ArrayList(){{
            add(new ArrayList(){{
                add("platform_sn");
                add("=");
                add(platform_sn);
            }});
        }};
        if(member_type.equals("1")){
            where.add(new ArrayList(){{
                add("wechat_openid");
                add("=");
                add(member.get("wechat_openid"));
            }});
        }else if(member_type.equals("2")){
            where.add(new ArrayList(){{
                add("alipay_userid");
                add("=");
                add(member.get("alipay_userid"));
            }});
        }else {
            return  "";
        }
        List<Map> hasMembers = db.table("member").where(where).select("sn");
        long create_time = System.currentTimeMillis();
        String last_login_ip = CommonUtil.getIpAddr();
        String token = "";
        String sn = "";
        int res = 0;
        Map updateData = new HashMap();
        updateData.put("avatar",member.get("avatar"));
        updateData.put("nickname",member.get("nickname"));
        updateData.put("sex",member.get("sex"));
        updateData.put("province",member.get("province"));
        updateData.put("city",member.get("city"));
        updateData.put("country",member.get("country"));
        updateData.put("last_login_time",create_time);
        updateData.put("last_login_ip",last_login_ip);

        if(null != member.get("unionid")){
            updateData.put("wechat_unionid",member.get("unionid"));
        }
        if(hasMembers.size() == 1){//如果用户存在：修改
            if(StringUtils.isBlank(updateData.get("avatar").toString())){
                updateData.remove("avatar");
            }
            if(StringUtils.isBlank(updateData.get("nickname").toString())){
                updateData.remove("nickname");
            }
            if(StringUtils.isBlank(updateData.get("province").toString())){
                updateData.remove("province");
            }
            if(StringUtils.isBlank(updateData.get("city").toString())){
                updateData.remove("city");
            }
            if(StringUtils.isBlank(updateData.get("sex").toString())){
                updateData.remove("sex");
            }

            res = db.table("member").where(where).update(updateData);
            sn = hasMembers.get(0).get("sn").toString();
        }else if(hasMembers.size() == 0){//如果用户不存在：新建
            sn = CommonUtil.createMemberSn();
            String operator_member_sn = "";
            String project_sn = "";
            updateData.put("sn",sn);
            updateData.put("platform_sn",platform_sn);
            updateData.put("type",member_type);
            updateData.put("mobile","");
            updateData.put("state","1");
            updateData.put("role","1");
            updateData.put("operator_member_sn",operator_member_sn);
            updateData.put("project_sn",project_sn);
            updateData.put("create_time",create_time);
            if(member_type.equals("1")){
                updateData.put("wechat_openid",member.get("wechat_openid"));
            }else if(member_type.equals("2")){
                updateData.put("alipay_userid",member.get("alipay_userid"));
            }
            res = db.table("member").insert(updateData);
            //若平台有新用户赠送金额
             if(res > 0 && Double.parseDouble(platform.get("new_member_free_money").toString()) > 0){
                String sql = "member_balance_change_proc(?, ?, ?, ?, ?, ?)";
                List parameter = new ArrayList<Object>();
                parameter.add(sn);
                parameter.add(7); //场景
                parameter.add(0); //实际金额
                parameter.add(platform.get("new_member_free_money"));  //赠送金额
                parameter.add("新会员赠送");  //备注
                parameter.add("");  //相关单号
                db.executeCall(sql, parameter, 1);
            }

        }else{
            return  "";
        }

        if(res > 0){
            return  sn;
        }

        return  "";

    }

    //获取会员身份列表
    @Override
    public List getRoles(String memberSn){
/*        JSONArray staffList = new JSONArray();

        List<LinkedHashMap<String, Object>> myBossList = staffService.findMyBossList(memberSn);
        LinkedHashMap<String, Object> newMyBossList = new LinkedHashMap<>();
        for (int i = 0; i < myBossList.size(); i++) {
            LinkedHashMap<String,Object> staff = new LinkedHashMap();
            JSONObject json = new JSONObject();
            json.put("role_id",myBossList.get(i).get("role_id"));
            json.put("role_name",myBossList.get(i).get("role_name"));
            if(null == newMyBossList.get(myBossList.get(i).get("operator_member_sn"))){
                JSONArray arr = new JSONArray();
                arr.add(json);
                staff.put("staff_member_sn",myBossList.get(i).get("staff_member_sn"));
                staff.put("operator_member_sn",myBossList.get(i).get("operator_member_sn"));
                staff.put("operatorName",myBossList.get(i).get("operatorName"));
                staff.put("staffs",arr);
                newMyBossList.put(myBossList.get(i).get("operator_member_sn").toString(),staff);
            }else{
                JSONObject jsonObject = JSONObject.fromObject(newMyBossList.get(myBossList.get(i).get("operator_member_sn")));
                JSONArray array = JSONArray.fromObject(jsonObject.get("staffs").toString());
                array.add(json);
                jsonObject.put("staff_member_sn",myBossList.get(i).get("staff_member_sn"));
                jsonObject.put("operator_member_sn",myBossList.get(i).get("operator_member_sn"));
                jsonObject.put("operatorName",myBossList.get(i).get("operatorName"));
                jsonObject.put("staffs",array);
                newMyBossList.put(myBossList.get(i).get("operator_member_sn").toString(),jsonObject);
            }
        }
        if (null != myBossList){

            Iterator it = newMyBossList.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                staffList.add(entry.getValue());
            }
        }*/

        //return  staffList;
        return  null;


        /*

        Map operatorMap = new HashMap();

        //查询是否为运营商
        DbUtil db = new DbUtil();
        String sql = "";
        List parameter = new ArrayList();
        sql = "select member.sn,operator.name,operator.member_sn as operator_member_sn from member left join operator on operator.member_sn = member.sn where member.sn = ? and member.role = 10";
        parameter.add(memberSn);
        List list = db.executeQueryBySql(sql, parameter);
        if(list.size() > 0){
            Map detail = (Map) list.get(0);
            operatorMap.put(detail.get("operator_member_sn").toString(),"1");
            result.add(detail);
        }

        //查询员工
        sql = "select member.sn,operator.name,operator.member_sn as operator_member_sn from staff left join member on member.sn = staff.staff_member_sn left join operator on operator.member_sn = staff.operator_member_sn where member.sn = ? and staff.state = 1";
        parameter = new ArrayList();
        parameter.add(memberSn);
        list = db.executeQueryBySql(sql, parameter);
        if(list.size() > 0){
            for (int i = 0; i < list.size(); i++) {
                Map detail = (Map) list.get(i);
                if(!operatorMap.containsKey(detail.get("operator_member_sn").toString())){
                    operatorMap.put(detail.get("operator_member_sn").toString(),"1");
                    result.add(detail);
                }
            }
        }*/


    }

    @Override
    public List<Member> queryByList(Integer pageIndex, Integer pageSize) {
        return memberDao.queryByList(pageIndex*pageSize+1,pageSize);
    }
}